﻿using CommonAdmin.Dto;
using CommonAdmin.Web.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text.Json.Nodes;

namespace CommonAdmin.Web.Controllers.Api
{
	[ApiController]
	[Route("api/[controller]")]
	public class LogController : ApiBaseController
	{
		public LogController(ILogger<LogController> logger, ISqlSugarClient db):base(logger, db) { }		
		/// <summary>
		/// 日志列表
		/// </summary>
		/// <param name="page"></param>
		/// <param name="limit"></param>
		/// <param name="keyword"></param>		
		/// <returns></returns>
		[HttpGet("list")]
		public JsonResult GetList(int page, int limit, string keyword)
		{
			ResultViewModel result = new ResultViewModel();
			try
			{
				result.code = (int)CodeEnum.请求成功;
				int total = 0;
				var list = _db.Queryable<LogDto>()
					.LeftJoin<UserDto>((l,u)=>l.UserId==u.Id)
					.Select((l, u) => new { Id = l.Id, UserName = u.Name, Content = l.Content, OldData = l.OldData, NewData = l.NewData, CreateTime = l.CreateTime })
					.MergeTable()
					.WhereIF(!string.IsNullOrWhiteSpace(keyword), o => o.Content.Contains(keyword) || o.OldData.Contains(keyword)||o.NewData.Contains(keyword))
					.OrderBy(o => o.CreateTime)
					.ToPageList(page, limit, ref total);
				result.rows = total;
				result.data = list;
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				base.LogError(ex, "获取日志列表失败");
			}
			return new JsonResult(result);
		}
		/// <summary>
		/// 删除日志
		/// </summary>
		/// <param name="data"></param>
		/// <returns></returns>
		[HttpPost("del")]
		public JsonResult Delete([FromBody] JsonObject data)
		{
			string id = data["id"]!.GetValue<string>();
			ResultViewModel result = new ResultViewModel();
			if (string.IsNullOrWhiteSpace(id))
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "日志Id不能为空";
				return new JsonResult(result);
			}			
			try
			{
				result.code = (int)CodeEnum.请求成功;
				_db.Deleteable<LogDto>(o=>o.Id==id).ExecuteCommand();
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				base.LogError(ex, "删除日志失败");
			}			
			return new JsonResult(result);
		}
	}
}
